package cn.njyd.corejava.thread.myday04;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{
    private Map<String,Object> map = new HashMap<>();

    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void put(String key,Object value) throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+"准备"+key+"和"+value+"设置到map中");
        Thread.sleep(1000);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"成功把数据："+key+"="+value+"写到map中");
    }

    public void putByWriterLock(String key,Object value) {
        rwLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"准备"+key+"和"+value+"设置到map中");
            Thread.sleep(1000);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"成功地把数据: "+key+"="+value+"写到map中");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public void get(String key) throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+"正准备从map中读取"+key+"对应的值");
        Thread.sleep(500);
        System.out.println(Thread.currentThread().getName()+"从map中读取到了："+key+"="+map.get(key));
    }

    public void getByReadLock(String key) throws InterruptedException {
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正准备从map中读取" + key + "对应的值");
            Thread.sleep(500);
            System.out.println(Thread.currentThread().getName() + "从map中读取到了：" + key + "=" + map.get(key));

        } finally {
            rwLock.readLock().unlock();
        }
    }

}

public class ReadWriterLockDemo01 {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i=1;i<=5;i++) {
            final int k = i;
            new Thread(()->{
                try {
                    myCache.putByWriterLock("key-"+k,"value-"+k);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },"用户"+i).start();
        }
        for (int i=1;i<=5;i++) {
            final int k = i;
            new Thread(()->{
                try {
                    myCache.getByReadLock("key-"+k);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },"用户"+i).start();
        }
    }
}
